package net.dntuan.training.mvc.security.authentication;

import java.util.*;

import net.dntuan.training.mvc.dao.UserDao;
import net.dntuan.training.mvc.security.Role;

import org.slf4j.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.*;

@Service("userDetailsServiceImpl")
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        net.dntuan.training.mvc.domain.User dbUser = this.userDao.getUserByUsername(username);
        logger.debug("dbUser is null? " + (dbUser == null));
        if (dbUser == null) {
            throw new UsernameNotFoundException("username is not found");
        }
        List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
        roles.add(Role.USER);

        User user = new User(dbUser.getUsername(), dbUser.getPassword(), dbUser.getEnable(), true, true, true, roles);
        return user;
    }

}
